package transport;

import java.io.IOException;

public class PacketTimer extends Thread {

	long begin;
	TransportConnection conn;
	boolean connected;
	byte[] data;
	int seq;

	/**
	 * Creates a timer
	 * 
	 * @param begin
	 *            == System.currentTimeMillis();
	 * @param conn
	 *            the connection that created the timer
	 */
	PacketTimer(long begin, TransportConnection conn,byte[] d, int s) {
		this.begin = begin;
		this.conn = conn;
		data = d;
		seq = s;		
		connected = true;

	}

	/**
	 * Runs the packet timer, starting a timer which will wait a set value of
	 * seconds, and when the timer runs out, resends the last received ack. Gets
	 * reset when an ack has been received.
	 */
	public void run() {
		
		while (!conn.getPacketList().isEmpty()&&connected&&conn.isConnected()&&conn.getPacketList().containsValue(data)) {
			
			try {
				Thread.sleep(Constants.TIMEOUT_VALUE);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (conn.getPacketList().containsKey(seq)) {
				try {
					try {
						if(connected){
						conn.data(
								data,
								seq);
						
						System.out
								.println("Timeout afgelopen, dus een resend van seq "
										+ conn.getLastReceivedACK());
						}
					} catch (NullPointerException e) {
						}
				} catch (IOException e) {

					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				this.dispose();
			}
		}
		
	}

	/**
	 * Resets the timer.
	 */
	public void resetBegin() {
		begin = System.currentTimeMillis();
	}
	
	public void dispose(){
		connected= false;
	}
}
